package com.jee.ssm.common.earthMagnet;


import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class SocketServer extends Thread{
    private Logger logger = Logger.getLogger(SocketServer.class);
    private Integer port = 8989;
    private boolean started = false;
    private ServerSocket ss = null;
    //private ExecutorService threadPool = Executors.newCachedThreadPool();
    private static final ExecutorService threadPool = new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());

    @Override
    public void run(){
        try {
            ss = new ServerSocket(port);
            started = true;
            logger.info("socket 地磁管理器 端口开启占用"+port+"端口号");
        } catch (BindException e){
            logger.info("端口使用中....");
            logger.info("请关掉相关程序并重新运行服务器！");
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        try {
            while (started) {
                Socket s = ss.accept();
                logger.info("一台管理器连接上了！");
                threadPool.execute(new Thread(new SocketHandle(s)));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            logger.info("连接异常，关闭socket服务");
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
